package com.zh.harmony.arch.core.executor;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 默认执行器
 */
public class DefaultTaskExecutor extends TaskExecutor {
    /**
     * 同步锁
     */
    private final Object mLock = new Object();

    /**
     * IO线程池
     */
    private final ExecutorService mDiskIO = Executors.newFixedThreadPool(4, new ThreadFactory() {
        private static final String THREAD_NAME_STEM = "arch_disk_io_%d";

        /**
         * 原子线程Id生成器
         */
        private final AtomicInteger mThreadId = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            //设置线程名称
            t.setName(String.format(THREAD_NAME_STEM, mThreadId.getAndIncrement()));
            return t;
        }
    });

    /**
     * 主线程EventHandler
     */
    private volatile EventHandler mMainHandler;

    @Override
    public void executeOnDiskIO(Runnable runnable) {
        mDiskIO.execute(runnable);
    }

    @Override
    public void postToMainThread(Runnable runnable) {
        if (mMainHandler == null) {
            synchronized (mLock) {
                if (mMainHandler == null) {
                    mMainHandler = new EventHandler(EventRunner.getMainEventRunner());
                }
            }
        }
        //noinspection ConstantConditions
        mMainHandler.postTask(runnable);
    }

    @Override
    public boolean isMainThread() {
        return EventRunner.getMainEventRunner().getThreadId() == Thread.currentThread().getId();
    }
}